<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      offset="20"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <van-cell
        v-for="(article, index) in list"
        :key="index"
        :title="article.title"
        @click="toArticleItemFn(article.art_id)"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchAPI } from '@/api'
export default {
  name: 'searchResultIndex',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  components: {},
  computed: {},
  created () {},
  mounted () {},
  watch: {},
  data () {
    return {
      loading: false,
      finished: false,
      error: false,
      page: 1,
      perPage: 20,
      list: []
    }
  },
  methods: {
    async onLoad () {
      try {
        if (this.searchText.trim().length === 0) return
        const { data } = await getSearchAPI({
          q: this.searchText,
          page: this.page,
          perPage: this.perPage
        })
        // console.log(data)
        const { results } = data.data
        this.list.push(...results)
        // 3. 设置加载状态结束
        this.loading = false

        // 4. 判断数据是否加载完毕
        if (results.length) {
          this.page++ // 更新获取下一页数据的页码
        } else {
          this.finished = true // 没有数据了，将加载状态设置结束，不再 onLoad
        }
      } catch (error) {
        this.error = true
        this.loading = false
        this.$toast('数据加载失败,请稍后重试')
      }
    },
    // 跳转到文章页面
    toArticleItemFn (artId) {
      this.$router.push('/article/' + artId)
    }
  }
}
</script>

<style lang="less" scoped></style>
